//获取应用实例
var app = getApp();
var reLoginNum = 0;
var timer = null;
var lock = false;

// 初始化数据
var init = {

  // 数据
  data: {

    // 总价
    totalAmount: 0,

    // 是否全选
    all: true,

    // 购物车ID
    recId: ''
  },

  // 页面第一次加载
  onLoad: function (options) {

    /*this.setData({
      options: options
    })*/

  },

  // 每次进来都执行
  onShow: function () {
    var that = this;
    // 登录授权
    app.getLoginSession(function (session) {
      that.getData(session);
    })
  },

  // 获取数据
  getData: function (session) {

    var that = this;

    // 请求前
    that.setData({

      // 开启loading
      loading: true
    });

    // 清空用户选择的数据
    wx.removeStorage({
      key: 'proDetailSelectData',
      success: function () {
        console.log('清除选中数据成功');
      }
    });

    // 请求
    wx.request({

      // 请求地址
      url: app.api,

      // 请求参数
      data: {
        app: 'cart',
        t_session: session
      },

      // 请求成功
      success: function (res) {
        var data = res.data;

        if (data.done) {
          if (data.retval.goods && data.retval.goods.length) {
            for (var i = 0; i < data.retval.goods.length; i++) {
              data.retval.goods[i].isSelected = true;
              data.retval.goods[i].itemId = data.retval.goods[i].goods_id + '' + data.retval.goods[i].spec_id + '' + data.retval.goods[i].rec_id;
            }
            console.log(data);

            that.setData({
              loading: false,
              data: data.retval,
              totalAmount: data.retval.total_price,
              recId: data.rec
            })
          } else {
            that.setData({
              errorTips: '暂无商品'
            })
          }
        } else {

          // 检查是否登录失败
          if (data.reLogin && (reLoginNum <= app.reLoginNum)) {
            app.login(function (session) {
              that.getData(session);
            });
            reLoginNum++;
          } else {
            that.setData({
              errorTips: data.msg || '请求错误，app:cart'
            })
          }
        }
      },

      // 请求失败
      fail: function () {
        that.setData({
          errorTips: '接口请求失败，app：cart'
        })
      }
    });

  },

  // 或者最终结果
  getSelect: function () {
    var data = that.data.data.goods;

  },

  // 单选选择
  selectOne: function (event) {
    var that = this;
    var id = event.currentTarget.dataset.id;
    var data = that.data.data.goods;
    var totalPrice = that.data.data.total_price;
    console.log(totalPrice);
    for (var i = 0; i < data.length; i++) {
      if (id == data[i].itemId) {
        data[i].isSelected = !data[i].isSelected

        // 实时计算价格
        if (data[i].isSelected) {
          console.log('a');
          totalPrice = (parseFloat(totalPrice) + parseFloat(data[i].price * data[i].quantity)).toFixed(2)
        } else {
          console.log('b');
          totalPrice = (parseFloat(totalPrice) - parseFloat(data[i].price * data[i].quantity)).toFixed(2)
        }
      }
    }
    that.setData({
      'data.goods': data,
      'data.total_price': totalPrice
    })
  },

  // 全选反选
  selectAll: function () {
    var that = this;
    var data = this.data.data.goods;
    var status = that.data.all ? false : true;
    for (var i = 0; i < data.length; i++) {
      data[i].isSelected = status;
    }
    that.setData({
      'data.goods': data,
      all: !that.data.all,
      'data.total_price': !that.data.all == false ? 0 : that.data.totalAmount
    })
  },

  // 修改数量
  changeNum: function (event) {

    // 加锁，避免连续快速点击
    if (lock) {
      console.log("a");
      return false;
    }
    lock = true;

    var that = this;
    var id = event.currentTarget.dataset.id;
    var type = event.currentTarget.dataset.type;
    var data = that.data.data.goods;

    app.getLoginSession(function (session) {
      for (var i = 0; i < data.length; i++) {

        if (id == data[i].itemId) {
          var item = data[i];

          // 计算num
          var quantity = item.quantity;
          if (type == 'add') {
            if (item.quantity < item.stock) {
              quantity = ++item.quantity;
            } else {
              quantity = item.stock;
              return
            }
          } else if (type == 'sub') {
            if (item.quantity <= 0) {
              quantity = 0;
              return;
            } else {
              quantity = --item.quantity;
            }
          }

          // 清除定时器
          if (timer) timer = null;

          // 延迟请求，避免连续快速点击
          timer = setTimeout(function () {
            wx: wx.request({
              url: app.api,
              data: {
                app: 'cart',
                act: 'update',
                rec_id: item.rec_id,
                goods_id: item.goods_id,
                spec_id: item.spec_id,
                quantity: quantity,
                t_session: session
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'POST',
              success: function (res) {
                if (res.data.retval) {
                  that.getData(session);
                }
              },
              fail: function (res) {

              },
              complete: function () {
                lock = false;
              }
            })
          }, 200)
          break;
        }
      }
    })

  },

  // 删除
  remove: function (event) {
    // 加锁，避免连续快速点击
    if (lock) return;
    lock = true;

    var that = this;
    var id = event.currentTarget.dataset.id;
    var data = that.data.data.goods;

    app.getLoginSession(function (session) {
      for (var i = 0; i < data.length; i++) {

        if (id == data[i].itemId) {
          var item = data[i];
          wx: wx.request({
            url: app.api,
            data: {
              app: 'cart',
              act: 'drop_ajax',
              rec_id: item.rec_id,
              t_session: session
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: function (res) {
              console.log(res.data);
              if (res.data.retval) {
                that.getData(session);
              }
            },
            fail: function (res) {

            },
            complete: function () {
              lock = false;
            }
          })
          break;
        }
      }
    })

  },

  // 结算
  settlement: function () {
    var that = this;
    var data = that.data.data.goods;
    var arr = [];
    for (var i = 0; i < data.length; i++) {
      if (data[i].isSelected) {
        arr.push(data[i].goods_id + '_' + data[i].spec_id + '_' + data[i].quantity);
      }
    }
    if (arr.length) {
      wx: wx.navigateTo({
        url: '/pages/confirmOrder/confirmOrder?checked_goods=' + arr.join() + '&fromcart=1'
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请选择要购买的商品',
        showCancel: false
      })
    }
  }

};

// 注册页面
Page(init);
